//
//  SendRedPacketVC.m
//  RPay
//
//  Created by hzy on 2017/10/31.
//  Copyright © 2017年 Charlie. All rights reserved.
//

#import "SendRedPacketVC.h"
#import "FriendServers.h"
#import "RefreshManager.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "PayValidationView.h"
#import "InputPswView.h"
#import "KKPlaceHolderTextView.h"
@interface SendRedPacketVC ()<UITextFieldDelegate,UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *numBackView;
@property (weak, nonatomic) IBOutlet UITextField *numTextF;
@property (weak, nonatomic) IBOutlet UITextField *moneyTextF;
@property (weak, nonatomic) IBOutlet KKPlaceHolderTextView *mesTextF;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *moneyViewCons;

@property (weak, nonatomic) IBOutlet UILabel *moneyLab;
@property (weak, nonatomic) IBOutlet UIButton *sendBtn;
@property (nonatomic,strong)PayValidationView *  payValidationView;
@property (nonatomic,strong)InputPswView *  inputPswView;
@property (nonatomic,assign)BOOL isHaveDian;


@end

@implementation SendRedPacketVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = _isSingle == YES?@"个人红包":@"群红包";
    [self setupUI];
    // Do any additional setup after loading the view from its nib.
}

-(void)setupUI{

    [self addNavigationBarLeftButtonItem];
    if (_isSingle == YES) {
    
        self.numBackView.hidden = YES;
        self.moneyViewCons.constant = 15;
        
    }
    self.mesTextF.delegate = self;
    self.mesTextF.placeholder = @"恭喜发财，大吉大利。";
    self.moneyTextF.delegate = self;
    self.numTextF.text = [NSString stringWithFormat:@"%@",self.pamas[@"redPacketCount"]];
    [_moneyTextF addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    
    

}
-(void)textFieldChanged:(UITextField *)textField{


    
        self.moneyLab.text = [NSString stringWithFormat:@"%.2f",[textField.text doubleValue]];


    


}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@""]) {
        
        return YES;
    }

    if (textView == _mesTextF) {
        if (textView.text.length>=50) {
            return NO;
        }
        NSString * str = [NSString stringWithFormat:@"%@%@",textView.text,text];
        if (str.length >50) {
            _mesTextF.text = [str substringWithRange:NSMakeRange(0, 50)];
            return NO;
        }
        
        return YES;
    }
    return YES;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{


    if ([string isEqualToString:@""]) {
        return YES;
    }

    
    
    if ([textField.text containsString:@"."]) {
        self.isHaveDian = YES;
    }else{
        self.isHaveDian = NO;
    }
    
    if (string.length > 0) {
        
        //当前输入的字符
        unichar single = [string characterAtIndex:0];

        
        // 不能输入.0-9以外的字符
        if (!((single >= '0' && single <= '9') || single == '.'))
        {

            return NO;
        }
        
        // 只能有一个小数点
        if (self.isHaveDian && single == '.') {

            return NO;
        }
        
        // 如果第一位是.则前面加上0.
        if ((textField.text.length == 0) && (single == '.')) {
            textField.text = @"0";
        }
        
        // 如果第一位是0则后面必须输入点，否则不能输入。
        if ([textField.text hasPrefix:@"0"]) {
            if (textField.text.length > 1) {
                NSString *secondStr = [textField.text substringWithRange:NSMakeRange(1, 1)];
                if (![secondStr isEqualToString:@"."]) {

                    return NO;
                }
            }else{
                if (![string isEqualToString:@"."]) {

                    return NO;
                }
            }
        }
        
        // 小数点后最多能输入两位
        if (self.isHaveDian) {
            NSRange ran = [textField.text rangeOfString:@"."];
            // 由于range.location是NSUInteger类型的，所以这里不能通过(range.location - ran.location)>2来判断
            if (range.location > ran.location) {
                if ([textField.text pathExtension].length > 1) {

                    return NO;
                }
            }
            
            
            
        }
        
    }
    

    
        NSMutableString* str1=[[NSMutableString alloc]initWithString:textField.text];
        [str1 insertString:string atIndex:range.location];
    
        if ([str1 integerValue] > 999999) {
            return NO;
        }

        
        

    
    
    
    
    
    return YES;

    
}
- (IBAction)sendBtnClick:(id)sender {

    [self.view endEditing:YES];
    

    if (!_mesTextF.text.length) {
        [_pamas setObject:_mesTextF.placeholder forKey:@"msg"];
    }else{
    
        [_pamas setObject:_mesTextF.text forKey:@"msg"];
    }
    [_pamas setObject:[ShareUser shareUser].userName forKey:@"userNumber"];
    if ([_moneyTextF.text doubleValue] < [_pamas[@"redPacketCount"] doubleValue]*0.01) {
        
        [self alertWithTitle:@"提示" message:@"请输入正确金额" handler:NULL];
        return;
    }
    
    [_pamas setObject:_moneyTextF.text forKey:@"money"];
    
    LAContext* context = [[LAContext alloc] init];
    NSError* error = nil;
    NSString* result = @"请验证已有指纹,用于支付";
    
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        [self showVefityView];
    }else if(error.code == LAErrorTouchIDLockout){
        [self showVefityView];
        
    }else{
        [self showPswView];
    }
    
    
    

    
    
}
-(void)showVefityView{
    MJWeakSelf
    _payValidationView = [[[NSBundle mainBundle] loadNibNamed:@"PayValidationView" owner:nil options:nil]lastObject];
    
    _payValidationView.frame = CGRectMake(0, 0, DEVICE_WITH, DEVICE_HEIGHT);
    _payValidationView.moneyLab.text = [NSString stringWithFormat:@"%@",_moneyTextF.text];
    _payValidationView.changeBlock = ^{
        [weakSelf showPswView];
        [weakSelf.payValidationView removeFromSuperview];
        
        
    };
    _payValidationView.sureBlock = ^{
        
        [weakSelf createLa];
        [weakSelf.payValidationView removeFromSuperview];
        
    };
    [[[[UIApplication sharedApplication]delegate]window]addSubview:_payValidationView];


    
}
-(void)showPswView{

    MJWeakSelf
    _inputPswView = [[[NSBundle mainBundle] loadNibNamed:@"InputPswView" owner:nil options:nil]lastObject];
    _inputPswView.moneyTextF.text = @"";
    _inputPswView.frame = CGRectMake(0, 0, DEVICE_WITH, DEVICE_HEIGHT);
    

    
    _inputPswView.sureBlock = ^{
        
        [weakSelf sendRedPacket:weakSelf.inputPswView.moneyTextF.text];
        [weakSelf.inputPswView removeFromSuperview];
    };
    [[[[UIApplication sharedApplication]delegate]window]addSubview:_inputPswView];
    [_inputPswView.moneyTextF becomeFirstResponder];


}
-(void)sendRedPacket:(NSString *)psw{
    
    
    if (psw) {
        [_pamas setObject:psw forKey:@"password"];
        [_pamas setObject:@"true" forKey:@"isCheckPassword"];
    }else{
    
        [_pamas setObject:@"" forKey:@"password"];
        [_pamas setObject:@"false" forKey:@"isCheckPassword"];
    }

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[FriendServers sharedInstance] PostNetworkWith:@"/open/appRedPacket/sendRedPacket.shtml" headerParams:nil formParams:self.pamas
                                           progress:^(NSProgress *progress) {
                                               
                                           } success:^(id responseObject) {
                                               [MBProgressHUD hideHUDForView:self.view animated:YES];
                                               if ([self checkNetworkData:responseObject]) {
                                                   [self alertWithTitle:@"提示" message:@"发送成功" handler:^(UIAlertAction *action) {
                                                       [self.navigationController popToRootViewControllerAnimated:YES];
                                                   }];
                                                   
                                                   
                                                   
                                                   
                                               }
                                               
                                               
                                           } failure:^(id responseObject) {
                                               
                                               [self alertNetworkError];
                                               [MBProgressHUD hideHUDForView:self.view animated:YES];
                                           }];
}
- (void)createLa
{
    //创建LAContext
    LAContext* context = [[LAContext alloc] init];
    NSError* error = nil;
    NSString* result = @"请验证已有指纹,用于支付";
    
    //首先使用canEvaluatePolicy 判断设备支持状态
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]||error.code == LAErrorTouchIDLockout) {
        //支持指纹验证
        
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:result reply:^(BOOL success, NSError *error) {
            if (success) {
                //验证成功，主线程处理UI
                NSLog(@"成功啦");

                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    
                    [self sendRedPacket:nil];
                    
                    
                    
                });
            }
            else
            {
                NSLog(@"%@",error.localizedDescription);
                switch (error.code) {

                    case LAErrorTouchIDLockout:
                        
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //用户选择输入密码，切换主线程处理
                            [context evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:@"请验证手机锁屏密码，解锁指纹" reply:^(BOOL success, NSError * _Nullable error) {
                                
                                if (success) {
                                    
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        
                                        
                                        [self createLa];
                                        
                                        
                                        
                                    });
                                }
                            }];
                            
                            
                        }];
                        

                        break;
                    }

                    case LAErrorUserFallback:
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //其他情况，切换主线程处理
                            [self showPswView];
                        }];
                        break;
                    }
                    default:
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //其他情况，切换主线程处理
                            [self showPswView];
                        }];
                        break;
                    }
                }
            }
        }];
    }
    else
    {
        [self showPswView];
        //不支持指纹识别，LOG出错误详情
        NSLog(@"不支持指纹识别");
        
        switch (error.code) {
            case LAErrorTouchIDNotEnrolled:
            {
                NSLog(@"TouchID is not enrolled");
                break;
            }
            case LAErrorPasscodeNotSet:
            {
                NSLog(@"A passcode has not been set");
                break;
            }
            default:
            {
                NSLog(@"TouchID not available");
                break;
            }
        }
        
        NSLog(@"%@",error.localizedDescription);
    }
}
@end
